package com.example.SocialApplication.activity.lists;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.example.SocialApplication.Daemon;
import com.example.SocialApplication.R;
import com.example.SocialApplication.activity.BaseActivity;
import com.example.SocialApplication.activity.lists.fragments.AddThingFragment;
import com.example.SocialApplication.activity.lists.fragments.DesignFragment;
import com.example.SocialApplication.activity.lists.fragments.PreferencesFragment;
import com.example.SocialApplication.activity.lists.fragments.ReadyFragment;
import com.example.SocialApplication.db.entity.User;

public class AddNewListActivity extends BaseActivity {

    private User user;
    private MyPageAdapter adapter;
    private ViewPager pager;
    private Button mButtonNext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        CreateListStatic.initListThings();

        mButtonNext = (Button) findViewById(R.id.main_layout_button_next);
        mButtonNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onCLickNext();
            }
        });

        TextView titleView = (TextView) findViewById(R.id.title_view);
        titleView.setVisibility(View.VISIBLE);
        titleView.setText("Новый список");

        user = Daemon.get("user", User.class);

        TextView textView = (TextView) findViewById(R.id.user_name);
        textView.setText(user.getFirstName() + " " + user.getLastName());

        ImageView view = (ImageView) findViewById(R.id.user_avatar);
        byte[] decodedString = Base64.decode(user.getPhoto(), Base64.DEFAULT);
        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        view.setImageBitmap(decodedByte);

        pager = (ViewPager) findViewById(R.id.pager);
        adapter = new MyPageAdapter(getSupportFragmentManager());
        pager.setAdapter(adapter);
        pager.setCurrentItem(0);

        final TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
        tabHost.setup();

        addTab(tabHost, tabHost.newTabSpec("design").setIndicator(prepareTabView(this, "ОФОРМЛЕНИЕ")), new TabInfo("design", new DesignFragment(), savedInstanceState));
        addTab(tabHost, tabHost.newTabSpec("add_thing").setIndicator(prepareTabView(this, "ДОБАВЛЕНИЕ ВЕЩЕЙ")), new TabInfo("add_thing", new AddThingFragment(), savedInstanceState));
        addTab(tabHost, tabHost.newTabSpec("preferences").setIndicator(prepareTabView(this, "ОБЩИЕ НАСТРОЙКИ")), new TabInfo("preferences", new PreferencesFragment(), savedInstanceState));
        addTab(tabHost, tabHost.newTabSpec("ready").setIndicator(prepareTabView(this, "ГОТОВО!")), new TabInfo("ready", new ReadyFragment(), savedInstanceState));

        tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                if (tabId.equals("design")) {
                    pager.setCurrentItem(0);
                } else if(tabId.equals("add_thing")) {
                    pager.setCurrentItem(1);
                } else if(tabId.equals("preferences")) {
                    pager.setCurrentItem(2);
                } else {
                    pager.setCurrentItem(3);
                }
            }
        });

        pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i2) {
                if(i == adapter.getCount()-1) {
                    mButtonNext.setText("Готово");
                } else {
                    mButtonNext.setText("Далее >>");
                }
            }

            @Override
            public void onPageSelected(int i) {
                tabHost.setCurrentTab(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });
    }

    private static View prepareTabView(Context context, String text) {
        View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
        TextView textView = (TextView) view.findViewById(R.id.tabsText);
        textView.setText(text);
        return view;
    }


    private void addTab(TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) {
        tabSpec.setContent(new TabFactory(this));
        String tag = tabSpec.getTag();

        tabInfo.fragment = getSupportFragmentManager().findFragmentByTag(tag);
        if (tabInfo.fragment != null && !tabInfo.fragment.isDetached()) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.detach(tabInfo.fragment);
            ft.commit();
            getSupportFragmentManager().executePendingTransactions();
        }
        tabHost.addTab(tabSpec);
    }

    private void onCLickNext() {
        if (pager.getCurrentItem() != 3) {
            pager.setCurrentItem(pager.getCurrentItem()+1);
        } else {
            Toast.makeText(this, "READY", Toast.LENGTH_SHORT).show();
            CreateListStatic.saveListThing();
            finish();
        }
    }

    private class MyPageAdapter extends FragmentStatePagerAdapter {

        public MyPageAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment = null;
            switch (position) {
                case 0:
                    fragment = new DesignFragment();
                    break;
                case 1:
                    fragment = new AddThingFragment();
                    break;
                case 2:
                    fragment = new PreferencesFragment();
                    break;
                case 3:
                    fragment = new ReadyFragment();
                    break;
            }
            return fragment;
        }

        @Override
        public int getCount() {
            return 4;
        }
    }

    private class TabInfo {
        private String tag;
        private Fragment clss;
        private Bundle args;
        private Fragment fragment;

        TabInfo(String tag, Fragment clazz, Bundle args) {
            this.tag = tag;
            this.clss = clazz;
            this.args = args;
        }
    }

    class TabFactory implements TabHost.TabContentFactory {

        private final Context mContext;

        public TabFactory(Context context) {
            mContext = context;
        }

        public View createTabContent(String tag) {
            View v = new View(mContext);
            v.setMinimumWidth(0);
            v.setMinimumHeight(0);
            return v;
        }
    }
}
